package com.zbkj.service.service.course.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zbkj.common.model.course.UserBaby;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.course.UserBabyRequest;
import com.zbkj.common.request.course.UserBabySearchRequest;
import com.zbkj.common.response.CommonResult;
import com.zbkj.service.dao.UserBabyDao;
import com.zbkj.service.service.SystemConfigService;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.course.UserBabyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @author Mr.guqianbin
* @description UserBabyServiceImpl 接口实现
* @date 2022-08-09
*/
@Service
public class UserBabyServiceImpl extends ServiceImpl<UserBabyDao, UserBaby> implements UserBabyService {

    @Resource
    private UserBabyDao dao;


    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfigService systemConfigService;

    /**
    * 列表
    * @param request 请求参数
    * @param pageParamRequest 分页类参数
    * @author Mr.guqianbin
    * @since 2022-08-09
    * @return List<UserBaby>
    */
    @Override
    public List<UserBaby> getList(UserBabySearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        Integer uid=userService.getUserId();
        if(ObjectUtil.isEmpty(request.getUid())&&uid!=0){
            request.setUid(uid);
        }
        //带 UserBaby 类的多条件查询
        LambdaQueryWrapper<UserBaby> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserBaby::getUid,request.getUid());
        if(request.getIsAll()==true){

        }else{
            lambdaQueryWrapper.eq(UserBaby::getIsKid,true);
        }
        return dao.selectList(lambdaQueryWrapper);
    }

    @Override
    public CommonResult<String> addBaby(UserBabyRequest request) throws Exception {
        UserBaby userBaby = new UserBaby();
        BeanUtils.copyProperties(request, userBaby);
        //图片上传类型 1本地 2七牛云 3OSS 4COS, 默认本地
        String uploadType = systemConfigService.getValueByKeyException("uploadType");
        Integer uploadTypeInt = Integer.parseInt(uploadType);
        String pre;
        String urlPrefix = systemConfigService.getValueByKey("localUploadUrl");
        switch (uploadTypeInt) {
            case 1:
                // 保存文件
//                multipartFile.transferTo(file);
                urlPrefix = systemConfigService.getValueByKey("localUploadUrl");
                break;
            case 2:
                pre = "qn";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");

                break;
            case 3:
                pre = "al";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");

                break;
            case 4:
                pre = "tx";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");
                break;
        }
        if(StringUtils.isNotEmpty(userBaby.getAvatar())){
            userBaby.setAvatar(StringUtils.remove(userBaby.getAvatar(),urlPrefix+"/"));
        }
        if(StringUtils.isNotEmpty(userBaby.getBirthday())){
            userBaby.setAge(getUserAge(DateUtil.parse(userBaby.getBirthday(),"yyyy-MM-dd")));
        }
        if(this.save(userBaby)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }
    public static String getAgeFromBirthTime(Date birthDay){
        Calendar cal = Calendar.getInstance();
        //得到当前时间的年月日
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);
        // 先截取到传入的年月日
        cal.setTime(birthDay);
        int paramYear = cal.get(Calendar.YEAR);
        int paramMonth = cal.get(Calendar.MONTH)+1;
        int paramDay = cal.get(Calendar.DAY_OF_MONTH);

        //用当前的年月日减去出生年月日
        int yearMinus = yearNow >= paramMonth ? yearNow - paramYear : 0;
        int monthMinus = monthNow >= paramMonth ? monthNow - paramMonth : 0;
        int dayMinus = dayNow >= paramDay ? dayNow - paramDay : 0;

        String ageToMonth = "";
        if(yearMinus > 0){
            ageToMonth = String.valueOf(yearMinus) + "岁";
        } else if((yearNow >= paramMonth) && monthMinus > 0){
            ageToMonth = String.valueOf(monthMinus) + "月";
        } else if((yearNow >= paramMonth) && (monthNow >= paramMonth) && dayMinus > 0){
            ageToMonth = String.valueOf(dayMinus) + "天";
        }
        return ageToMonth;
    }
    public static  int getUserAge(Date birthDay) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDayAge = sdf.parse(sdf.format(birthDay));
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDayAge)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "日期填写错误！！");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDayAge);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;//当前日期在生日之前，年龄减一
                }
            }else{
                age--;//当前月份在生日之前，年龄减一
            } } return age;
    }

    @Override
    public CommonResult<String> updateBaby(UserBabyRequest request) throws Exception {
        UserBaby userBaby = new UserBaby();
        BeanUtils.copyProperties(request, userBaby);
        //图片上传类型 1本地 2七牛云 3OSS 4COS, 默认本地
        String uploadType = systemConfigService.getValueByKeyException("uploadType");
        Integer uploadTypeInt = Integer.parseInt(uploadType);
        String pre;
        String urlPrefix = systemConfigService.getValueByKey("localUploadUrl");
        switch (uploadTypeInt) {
            case 1:
                // 保存文件
//                multipartFile.transferTo(file);
                urlPrefix = systemConfigService.getValueByKey("localUploadUrl");
                break;
            case 2:
                pre = "qn";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");

                break;
            case 3:
                pre = "al";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");

                break;
            case 4:
                pre = "tx";
                urlPrefix= systemConfigService.getValueByKeyException(pre+"UploadUrl");
                break;
        }
        if(StringUtils.isNotEmpty(userBaby.getAvatar())){
            userBaby.setAvatar(StringUtils.remove(userBaby.getAvatar(),urlPrefix+"/"));
        }
        if(StringUtils.isNotEmpty(userBaby.getBirthday())){
            userBaby.setAge(getUserAge(DateUtil.parse(userBaby.getBirthday(),"yyyy-MM-dd")));
        }
        if(this.updateById(userBaby)){
            return CommonResult.success();
        }else{
            return CommonResult.failed();
        }
    }

}

